package com.distribute.framework.core.web.helper;

import com.distribute.framework.core.util.Api;
import com.distribute.framework.core.util.CoordTransformUtil;
import com.distribute.framework.core.util.Excel;
import com.distribute.framework.core.util.zip.ZipEntry;
import com.distribute.framework.core.util.zip.ZipOutputStream;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.Deflater;
import java.util.zip.GZIPOutputStream;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import com.distribute.framework.core.lang.Protocol;
import com.distribute.framework.core.sql.Lazy3qDaoSupport;
import com.distribute.framework.core.sql.Lazy3qSQL;
import com.distribute.framework.core.sql.mongodb.MongodbDataSource;
import com.distribute.framework.core.sql.redis.RedisSupport;
import com.distribute.framework.core.web.helper.*;
import com.distribute.framework.core.web.util.RandomValidateCodeUtil;
import com.distribute.framework.core.xwork.WebContext;

public class Utils extends WebHelper {
	
	public static enum TIME{
		SECOND(1000l),
		MINUTE(1000l*60l),
		HOUR(1000l*60l*60l),
		DAY(1000l*60l*60l*24),
		MONTH(1000l*60l*60l*24*31),
		YEAR(1000l*60l*60l*365);
		public long time=0; 
		TIME(long time){
			this.time = time;
		}
	}
	
	public static class GPS extends CoordTransformUtil{}
	
	public static Lazy3qDaoSupport getDao(String source){
		return Lazy3qSQL.GetDao(source);
	}
	
	public static Map getJson(Map<String,Object> params, String key){
		return ParamHelper.getJson(params,key, null);
	}
	
	public static Map getJson(Map<String,Object> params, String key,Map defaultValue){
		return ParamHelper.getJson(params,key, null);
	}
		
	public static String getString(Map<String,Object> params, String key){
		return ParamHelper.getString(params,key, null);
	}
	
	public static String getString(Map<String,Object> params, String key,String defaultValue){
		return ParamHelper.getString(params,key, defaultValue);
	}
	
	public static Double getDouble(Map<String,Object> params, String key){
		return ParamHelper.getDouble(params,key, null);
	}
	
	public static Double getDouble(Map<String,Object> params, String key, Double defaultValue){
		return ParamHelper.getDouble(params,key, defaultValue);
	}
	
	public static Integer getInteger(Map<String,Object> params, String key){
		return ParamHelper.getInteger(params, key, null);
	}
	
	public static Integer getInteger(Map<String,Object> params, String key,Integer defaultValue){
		return ParamHelper.getInteger(params, key, defaultValue);
	}
	public static Short getShort(Map<String,Object> params, String key){
		return ParamHelper.getShort(params, key, null);
	}
	public static Short getShort(Map<String,Object> params, String key,Short defaultValue){
		return ParamHelper.getShort(params, key, defaultValue);
	}
	public static Long getLong(Map<String,Object> params, String key){
		return ParamHelper.getLong(params, key, null);
	}
	
	public static Long getLong(Map<String,Object> params, String key, Long defaultValue){
		return ParamHelper.getLong(params, key, defaultValue);
	}
	
	public static Byte getByte(Map<String,Object> params, String key){
		return ParamHelper.getByte(params, key, null);
	}
	
	public static Byte getByte(Map<String,Object> params, String key,Byte defaultValue){
		return ParamHelper.getByte(params, key, defaultValue);
	}
	
	public static Boolean getBoolean(Map<String,Object> params, String key)
	{
		return ParamHelper.getBoolean(params, key, null);
	}
	
	public static Boolean getBoolean(Map<String,Object> params, String key,Boolean defaultValue)
	{
		return ParamHelper.getBoolean(params, key, defaultValue);
	}

	public static Date getDate(Map<String,Object> params, String key){
		return ParamHelper.getDate(params, key, null);
	}
	
	public static Date getDate(Map<String,Object> params, String key,Date defaultValue){
		return ParamHelper.getDate(params, key, defaultValue);
	}

	public static String[] getArray(Map<String,Object> params,String key){
		return ParamHelper.getArray(params, key, null);
	}	
	
	public static String[] getArray(Map<String,Object> params,String key,String[] defaultValue){
		return ParamHelper.getArray(params, key, defaultValue);
	}
	
	public static Float getFloat(Map<String,Object> params, String key){
		return ParamHelper.getFloat(params, key, null);
	}
	
	public static Float getFloat(Map<String,Object> params, String key, Float defaultValue){
		return ParamHelper.getFloat(params, key, defaultValue);
	}
	
	public static <T> T getObject(Map params,String key,Class<T> cls)
	{
		return (T) ParamHelper.getObject(params, key, cls);
	}

	public static String getArrayToString(Map<String,Object> params,String key, String join) {
		return ParamHelper.getArrayToString(params, key, join);
	}	

	public static String getQueryString(Map<String,Object> params,String charset,String... notAt){
		return ParamHelper.getQueryString(params, charset, notAt);
	}
	
	public static Excel excel(File file){
		return Excel.parse(file);
	}
	
	public static void putQueryStringNotAt(String key){
		Utils.setRequest("notat."+key, true);
	}
	
	public static Map params(){
		if(WebContext.getServletRequest()!=null){
			return WebContext.getServletRequest().getParameterMap();
		}else{
			return new HashMap();
		}
	}
	/**
	 * 
	 * @param strUrl
	 * @param postString
	 * @return
	 * String
	 */
	@SuppressWarnings("deprecation")
	public static String doPost(String strUrl, String postString) {
		String receive = null;
		
		// 请求发布在本地 Tomcat上服务
		PostMethod method = new PostMethod(strUrl);
//		PostMethod method = new PostMethod();
		try {
			HttpClient client = new HttpClient();
//			client.getHostConfiguration().setHost(new HttpHost());
			
			//请求 网络上的服务, 用这种方式请求本地,返回一个Html页面
//			client.getHostConfiguration().setHost(new URI(strUrl));
			
			method.setRequestHeader("Content-type", "application/json; charset=UTF-8");
			method.setRequestHeader("Accept", "application/json; charset=UTF-8");
			// 设置为默认的重试策略
			method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
			
			// 4, 设置请求参数(请求内容)
/*			NameValuePair pair1 = new NameValuePair("key", "value");
			NameValuePair pair2 = new NameValuePair("key", "value");
			method.setRequestBody(new NameValuePair[]{pair1, pair2} );*/
 
			method.setRequestBody(postString);
			int rspCode = client.executeMethod(method);
			//
			System.out.println("rspCode:" + rspCode);
			receive = method.getResponseBodyAsString();
			System.out.println("receive:" + receive);
			return receive;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			method.releaseConnection();
		}
		return receive;
	}
	public static Map getJson(String key){
		return ParamHelper.getJson(params(),key, null);
	}
	
	public static Map getJson(String key,Map defaultValue){
		return ParamHelper.getJson(params(),key, null);
	}
	
	public static String getString( String key){		
		return ParamHelper.getString(params(),key, null);
	}
	
	public static String getString( String key,String defaultValue){
		return ParamHelper.getString(params(),key, defaultValue);
	}
	
	public static Double getDouble( String key){
		return ParamHelper.getDouble(params(),key, null);
	}
	
	public static Double getDouble( String key, Double defaultValue){
		return ParamHelper.getDouble(params(),key, defaultValue);
	}
	
	public static Integer getInteger( String key){
		return ParamHelper.getInteger(params(), key, null);
	}
	
	public static Integer getInteger( String key,Integer defaultValue){
		return ParamHelper.getInteger(params(), key, defaultValue);
	}
	public static Short getShort( String key){
		return ParamHelper.getShort(params(), key, null);
	}
	public static Short getShort( String key,Short defaultValue){
		return ParamHelper.getShort(params(), key, defaultValue);
	}
	public static Long getLong( String key){
		return ParamHelper.getLong(params(), key, null);
	}
	
	public static Long getLong( String key, Long defaultValue){
		return ParamHelper.getLong(params(), key, defaultValue);
	}
	
	public static Byte getByte( String key){
		return ParamHelper.getByte(params(), key, null);
	}
	
	public static Byte getByte( String key,Byte defaultValue){
		return ParamHelper.getByte(params(), key, defaultValue);
	}
	
	public static Boolean getBoolean( String key)
	{
		return ParamHelper.getBoolean(params(), key, null);
	}
	
	public static Boolean getBoolean( String key,Boolean defaultValue)
	{
		return ParamHelper.getBoolean(params(), key, defaultValue);
	}

	public static Date getDate( String key){
		return ParamHelper.getDate(params(), key, null);
	}
	
	public static Date getDate( String key,Date defaultValue){
		return ParamHelper.getDate(params(), key, defaultValue);
	}

	public static String[] getArray(String key){
		return ParamHelper.getArray(params(), key, null);
	}	
	
	public static String[] getArray(String key,String[] defaultValue){
		return ParamHelper.getArray(params(), key, defaultValue);
	}
	
	public static Float getFloat( String key){
		return ParamHelper.getFloat(params(), key, null);
	}
	
	public static Float getFloat( String key, Float defaultValue){
		return ParamHelper.getFloat(params(), key, defaultValue);
	}
	
	public static <T> T getObject(String key,Class<T> cls)
	{
		return (T) ParamHelper.getObject(params(), key, cls);
	}

	public static String getArrayToString(String key, String join) {
		return ParamHelper.getArrayToString(params(), key, join);
	}	

	public static String getQueryString(String charset,String... notAt){
		return ParamHelper.getQueryString(params(), charset, notAt);
	}
	
	public static String config(String key){
		return ConfigHelper.GetString(key);
	}
	public static Map<String,Object> Obj2Map(Object obj) throws Exception{
	   Map<String, Object> map=new HashMap<String, Object>();
	     Field[] fields = obj.getClass().getDeclaredFields();
			 for(Field field:fields){
			     field.setAccessible(true);
			     map.put(field.getName(), field.get(obj));
			}
      return map;
	}
	public static String config(String key,String defaultValue){
		String value = ConfigHelper.GetString(key);
		return Utils.empty(value)?defaultValue:value;
	}
		
	
	public static void getRandcode(){
		RandomValidateCodeUtil.getRandcode();
	}
	
	
	/**
	 * 写文件
	 * @param string
	 * @param fileName
	 */
	public static void writeFile(String fileName,String content,String encode)
	{		
		FileHelper.writeFile(fileName, content, encode);
	}
	
	/**
	 * 读文件
	 * @param srcFilename
	 * @param encode
	 * @return 文件内容
	 * @throws Exception
	 */
	public static String readFile(String srcFilename) throws Exception
	{	
		return FileHelper.readFile(srcFilename);
	}
	
	/**
	 * 读文件
	 * @param srcFilename
	 * @param encode
	 * @return 文件内容
	 * @throws Exception
	 */
	public static String readFile(InputStream input,String encode) throws Exception
	{	
		return FileHelper.readFile(input, encode);
	}

	/**
	 * 写流到文件
	 * @param input
	 * @param destFilename
	 * @return
	 * @throws Exception
	 */
	public static String writeStreamToFile(InputStream input, String fileName)throws Exception
	{
		return FileHelper.writeStreamToFile(input, fileName);
	}
	
	public static String getCharset(String filename) {
		return FileHelper.getCharset(filename);		
	}
	
	/**
	 * 获取文件编码
	 * @param file
	 * @return
	 * ANSI：无格式定义；
	 * Unicode： 前两个字节为FFFE；
	 * Unicode big endian：前两字节为FEFF；　 
	 * UTF-8：前两字节为EFBB；
	 */
	public static String getCharset( InputStream is ) {   
        return FileHelper.getCharset(is);
    }
	
	/**
	 * 压缩文件
	 * @param filename
	 * @param files
	 * @throws Exception
	 */
	public static void zip(File zipFile, File...files) throws Exception
	{
		FileHelper.zip(zipFile, files);
	}
	
	
	public static Protocol api(String url, String appid, String secret,String method,String token,Map params,Integer timeout){
		return Api.execue(url, appid, secret, method, token, params, timeout);
	}
	
    
    public static void main(String...strings){
    	try {
			//Utils.api(url, appid, secret, method, token, params, timeout);
		} catch (Exception e) {
			e.printStackTrace();
		}    	
    }
	
	public static RedisSupport getRedis(String name){
		return RedisSupport.getRedis(name);
	}
	
	
	public static MongodbDataSource getMongo(String name){
		return MongodbDataSource.getMongodbDataSource(name);
	}
	
	
	/**********************cookie操作部分*************************/
	public static Cookie getCookie(String name){
		return CookieHelper.getCookie(name);
	}
	public static String cookie(String name){
		return CookieHelper.getCookieValue(name);
	}
	public static void cookie(String domain,String path,String name,String value,int time){
		CookieHelper.setCookie(domain, path, name, value, time);
	}
	public static void delCookie(String domain,String path,String name){
		CookieHelper.delCookie(domain,path,name);
	}
	public static void delCookie(String domain,String path){
		CookieHelper.clear(domain,path);
	}
	
	public static HttpServletResponse getServletResponse()
	{
		return WebContext.getServletResponse();
	}
	public static HttpSession getHttpSession()
	{
		return WebContext.getHttpSession();
	}
	public static HttpServletRequest getServletRequest()
	{
		return WebContext.getServletRequest();
	}
	public static ServletContext getServletContext()
	{
		return WebContext.getServletContext();
	}

	
}